﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Nero_demo.Westward
{
    class TaskManager
    {
        public TaskManager(string initName)
        {
            this.initName = initName;
            serialNum = 1;
        }

        public void InitProcList()
        {
            if (procList == null)
            {
                procList = new List<ProcessHelper>();
                DetectNewProc();
            }
        }

        public bool StartArenaTask(out string result)
        {
            if (!RefreshProcList())
            {
                result = "未找到游戏窗口";
                return false;
            }

            Resource player = new Resource("Player");
            foreach (var proc in procList)
            {
                proc.Player = player;
                StartBackgroundTask(new ThreadStart(proc.ArenaTask));
            }
            result = string.Empty;
            return true;
        }

        private void DetectNewProc()
        {
            ProcessHelper proc = new ProcessHelper();
            proc.Name = initName;

            while (proc.InitWindow())
            {
                string newName = initName + "#" + serialNum.ToString();
                proc.ChangeName(newName);
                procList.Add(proc);
                serialNum++;
                proc = new ProcessHelper();
                proc.Name = initName;
            }
        }

        private bool RefreshProcList()
        {
            if (procList == null)
            {
                InitProcList();
            }
            else
            {
                procList.RemoveAll(proc => !proc.InitWindow());
                DetectNewProc();
            }

            return procList.Count != 0;
        }

        private void StartBackgroundTask(ThreadStart ts)
        {
            Thread myThread = new Thread(ts);//实例化Thread线程类对象
            myThread.IsBackground = true;
            myThread.Start();
        }

        public void OnExit()
        {
            if (procList != null)
            {
                foreach (var proc in procList)
                {
                    proc.ChangeName(initName);
                }
            }
        }


        private string initName;
        private int serialNum;
        private List<ProcessHelper> procList;
    }
}
